var maxWaitTime = 1000;
var currentWait = 0;

console.debug("CS: Initiating... ");
init();

var myport = chrome.extension.connect();


myport.onMessage.addListener(handleMessage);

function handleMessage(settings) {
	
	console.debug("CS: Handling received settings...");
	console.debug(settings);
	
	console.debug("CS: Start customizing...");
	console.debug(settings);
	customizeNewTab(settings);
	console.debug("CS: Done customizing...");
	
	if(settings["displayAnotherPageInstead"] != "1"){
		showBody();
	}
	
	console.debug("CS: Done handling received settings...");
}

function init() {
	var theBody = document.body;
	
	if(theBody == null){
		console.debug("CS: Body not loaded yet...");
		if(currentWait < maxWaitTime){
			currentWait++;
			window.setTimeout(init,1);
		} else {
			currentWait=0;
		}
		return;
	}
	console.debug("CS: Hiding body...");
	theBody.style.display = "none";
	console.debug("CS: Sending message...");
	myport.postMessage("getsettings");
	console.debug("CS: Done sending message...");
}

function showBody() {
	console.debug("CS: Showing body...");
	document.body.style.display = "block";
}

function customizeNewTab(settings) {
	
	if(document.body == null)
	{
		console.debug("CS: Cannot customize, no body");
		window.setTimeout(customizeNewTab,1,settings);
		return;
	}
	
	if(settings['displayAnotherPageInstead']=="1"){
		console.debug("CS: Redirecting");
		window.location = settings['pageToDisplayURL'];
		return;
	}
	if(settings['displayAnotherPageInstead']=="2"){
		console.debug("CS: Adding IFrame");
		addPageIFrame(settings['pageToDisplayURL']);
	}

	if(settings['hideMostVisited'] == "true")
		removeDiv("mostvisitedsection");
	if(settings['hideSearches'] == "true")
		hideDiv("searches");
	if(settings['hideRecentBookmarks'] == "true")
		hideDiv("recentlyBookmarked");
	if(settings['hideRecentlyClosedTabs'] == "true")
		hideDiv("recentlyClosedTabs");
		
}

function hideDiv(divName){
	var theDiv = document.getElementById(divName);

	if(theDiv == null){
		if(currentWait < maxWaitTime){
			currentWait++;
			window.setTimeout(hideDiv,1,divName);
		} else {
			currentWait=0;
		}
		return;
	}
	
	theDiv.style.visibility = "hidden";
}

function removeDiv(divName){
	var theDiv = document.getElementById(divName);

	if(theDiv == null){
		if(currentWait < maxWaitTime){
			currentWait++;
			window.setTimeout(removeDiv,1,divName);
		} else {
			currentWait=0;
		}
		return;
	}
	
	theDiv.parentNode.removeChild(theDiv);
}

function addPageIFrame(theURL){
	frame = document.createElement("IFRAME");
	frame.setAttribute("src", theURL);
	frame.style.width = 100+"%";
	frame.style.height = 50+"%";
	
	var theBody = document.body;
	if(theBody == null){
		if(currentWait < maxWaitTime){
			currentWait++;
			window.setTimeout(addPageIFrame,1,theURL);
		} else {
			return;
		}
	} else {
		theBody.insertBefore(frame, theBody.firstChild);
	}
}